//
//  IGRegisterViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGRegisterViewController.h"

@interface IGRegisterViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phone;

@property (weak, nonatomic) IBOutlet UITextField *name;


@property (weak, nonatomic) IBOutlet UITextField *code;

@property (weak, nonatomic) IBOutlet UITextField *password;

@property (weak, nonatomic) IBOutlet UIButton *sendCodeButton;
@property (weak, nonatomic) IBOutlet UIButton *registButton;

@property (nonatomic, strong) UILabel *promptLabel;
@property (nonatomic, assign) NSInteger timeCount;
@property (nonatomic, assign) BOOL isSendCode;

@end

@implementation IGRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _isSendCode = NO;
    _timeCount = 60;
}
- (IBAction)registerClick:(UIButton *)sender {
    // post http://www.imbatv.cn/api_2_4_0/registerUser
    // nickname=%E5%A5%B6%E6%B5%B4&password=123456789&username=18721890734&yzm=14348
    if (_phone.text.length == 0) {
        [self addPromptLabelWithStr:@"请输入手机号"];
        return;
    }
    
    if (_code.text.length == 0) {
        [self addPromptLabelWithStr:@"请输入验证码"];
        return;
    }
    
    if (_name.text.length == 0) {
        [self addPromptLabelWithStr:@"昵称必填"];
        return;
    }
    
    if (_password.text.length == 0) {
        [self addPromptLabelWithStr:@"密码必填"];
        return;
    }
    
    [self requestIsRegistSuccess];
}

// 点击注册按钮后,请求判断是否注册成功
- (void)requestIsRegistSuccess
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"nickname"] = [_name.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    dic[@"password"] = _password.text;
    dic[@"username"] = _phone.text;
    dic[@"yzm"] = _code.text;
    [IGAFNetworking newRequestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/registerUser" parDic:dic method:POST finish:^(NSDictionary *dataDic) {
        [self addPromptLabelWithStr:dataDic[@"message"]];
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];
}

- (IBAction)back:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (IBAction)sendCode:(UIButton *)sender {
    
    NSString *phoneNumber = _phone.text;
    if (phoneNumber.length != 11 || ![[phoneNumber substringToIndex:1] isEqualToString:@"1"]) {
        [self addPromptLabelWithStr:@"请输入正确的手机号码"];
        return;
    }
    _isSendCode = YES;
    [self requestSendCodeWithPhoneNumber:phoneNumber];
    _sendCodeButton.userInteractionEnabled = NO;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    [timer fire];
}

- (void)timer:(NSTimer *)timer
{
    _timeCount --;
    NSString *title = [NSString stringWithFormat:@"%ld秒后重新发送",_timeCount];
    [_sendCodeButton setTitle:title forState:(UIControlStateNormal)];
    if (_timeCount == 0) {
        [_sendCodeButton setTitle:@"发送验证码" forState:(UIControlStateNormal)];
        _sendCodeButton.userInteractionEnabled = YES;
        _isSendCode = NO;
        _timeCount = 60;
        [timer invalidate];
    }
}

// 判断输入的是不是数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    if(textField == _phone)
    {
        cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789\n"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)
        {
           [self addPromptLabelWithStr:@"手机号码只能为数字"];
           return NO;
        }
    }
    return YES;
}

// 手机号码输入正确后请求数据 发送验证码
- (void)requestSendCodeWithPhoneNumber:(NSString *)phoneNumber
{
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleShrink];
    [MMProgressHUD showWithTitle:nil status:@"正在发送中"];
    NSString *urlString = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getYzm?username=%@",phoneNumber];
    [IGAFNetworking requestWithUrlString:urlString parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        [MMProgressHUD dismiss];
        [self addPromptLabelWithStr:dataDic[@"message"]];
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];
}

// 添加label提示
- (void)addPromptLabelWithStr:(NSString *)str
{
    _registButton.userInteractionEnabled = NO;
    _sendCodeButton.userInteractionEnabled = NO;
    _promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, (kScreenHeight - 50)/2, kScreenWidth - 160, 50)];
    _promptLabel.backgroundColor = [UIColor blackColor];
    _promptLabel.alpha = 0.7;
    _promptLabel.text = str;
    _promptLabel.textColor = [UIColor whiteColor];
    _promptLabel.textAlignment = NSTextAlignmentCenter;
    _promptLabel.layer.cornerRadius = 10;
    _promptLabel.layer.masksToBounds = 10;
    [self.view addSubview:_promptLabel];
    [self performSelector:@selector(deleteLabel) withObject:nil afterDelay:1];
}

- (void)deleteLabel
{
    [_promptLabel removeFromSuperview];
    if (!_isSendCode) {
        _sendCodeButton.userInteractionEnabled = YES;
    }
    _registButton.userInteractionEnabled = YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [_name resignFirstResponder];
    [_password resignFirstResponder];
    [_phone resignFirstResponder];
    [_code resignFirstResponder];

    return YES;
    
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_name resignFirstResponder];
    [_password resignFirstResponder];
    [_phone resignFirstResponder];
    [_code resignFirstResponder];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
